package com.itheima.service.impl;

import com.itheima.dao.DeptMapper;
import com.itheima.dao.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;
    @Override
    public List<Dept> getDeptList() {
        //调用dao层，获取部门数据
        List<Dept> deptList = deptMapper.findAllDept();

        if(deptList!=null&&deptList.size()>0){
            return deptList;
        }
       return null;
    }

    @Override
    public void delete(Integer id) {
        deptMapper.delete(id);
    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }

    @Override
    public Dept selectById(Integer id) {

        return deptMapper.findDeptById(id);
    }
    @Override
    public void deleteEmpById(Integer id) {
    try{
        deptMapper.deleteDeptById(id);
        if(true) {
            throw new RuntimeException("出现异常");
        }
        empMapper.deleteEmpByDeptId(id);
    }finally {
        DeptLog deptLog = new DeptLog();
        deptLog.setCreateTime(LocalDateTime.now());
        deptLog.setDescription("执行了解散部门的操作解散部门的id是"+id+"号部门");
        deptLogService.insert(deptLog);
    }
    }

}
